package medicalDocumentation.medicalRepository;

import entity.NursingProcedure;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class NursingProcedureRepositorySessionBean implements NursingProcedureRepositorySessionBeanRemote {

    public final String NURSING_PROCEDURE_CODE_REQUIRED = "Nursing procedure code required";
    public final String DUPLICATE_NURSING_PROCEDURE_CODE = "Duplicate nursing procedure code";
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public String addNursingProcedure(String code, String name,String procedure, String remark) {
        if (code == null) {
            return NURSING_PROCEDURE_CODE_REQUIRED;
        }
        if (getNursingProcedureByCode(code).size() > 0) {
            return DUPLICATE_NURSING_PROCEDURE_CODE;
        }
        NursingProcedure nursingProcedure = new NursingProcedure();
        nursingProcedure.setCode(code);
        nursingProcedure.setName(name);
        nursingProcedure.setProcedure(procedure);
        nursingProcedure.setRemark(remark);
        entityManager.persist(nursingProcedure);
        entityManager.flush();
        return nursingProcedure.getCode();
    }

    @Override
    public List<NursingProcedure> getNursingProcedureByCode(String code) {
        String strQuery = "SELECT d FROM NursingProcedure d WHERE d.code = :inCode";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inCode", code);
        return query.getResultList();
    }

    @Override
    public List<NursingProcedure> getAllNursingProcedure() {
        String strQuery = "SELECT m FROM NursingProcedure m";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    @Override
    public void deleteNursingProcedure(String code) {
        List nursingProcedures = getNursingProcedureByCode(code);
        if (nursingProcedures.get(0) != null) {
            entityManager.remove(nursingProcedures.get(0));
            entityManager.flush();
        }
    }

    @Override
    public void updateNursingProcedure(String code, String name, String procedure, String remark) {
        NursingProcedure nursingProcedure = getNursingProcedureByCode(code).get(0);
        if (nursingProcedure != null) {
            nursingProcedure.setName(name);
            nursingProcedure.setProcedure(procedure);
            nursingProcedure.setRemark(remark);
            entityManager.merge(nursingProcedure);
            entityManager.flush();
        }
    }
}
